package com.kuang.exam.modules.user.exam.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kuang.exam.core.api.dto.PagingReqDTO;
import com.kuang.exam.core.exception.ServiceException;
import com.kuang.exam.modules.enums.OpenType;
import com.kuang.exam.modules.exam.entity.Exam;
import com.kuang.exam.modules.exam.entity.ExamLesson;
import com.kuang.exam.modules.exam.service.ExamDepartService;
import com.kuang.exam.modules.exam.service.ExamLessonService;
import com.kuang.exam.modules.exam.service.ExamService;
import com.kuang.exam.modules.paper.service.PaperService;
import com.kuang.exam.modules.sys.depart.service.SysDepartService;
import com.kuang.exam.modules.sys.lesson.service.SysUserLessonService;
import com.kuang.exam.modules.sys.user.service.SysUserService;
import com.kuang.exam.modules.user.UserUtils;
import com.kuang.exam.modules.user.exam.dto.request.UserExamReqDTO;
import com.kuang.exam.modules.user.exam.dto.response.ExamStatisticsRespDTO;
import com.kuang.exam.modules.user.exam.dto.response.UserExamRespDTO;
import com.kuang.exam.modules.user.exam.entity.UserExam;
import com.kuang.exam.modules.user.exam.mapper.UserExamMapper;
import com.kuang.exam.modules.user.exam.service.UserExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 考试记录业务实现类
 * </p>
 */
@Service
public class UserExamServiceImpl extends ServiceImpl<UserExamMapper, UserExam> implements UserExamService {

    @Autowired
    private ExamService examService;

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysDepartService departService;

    @Autowired
    private ExamDepartService examDepartService;

    @Autowired
    private ExamLessonService examLessonService;

    @Autowired
    private SysUserLessonService userLessonService;

    @Autowired
    private PaperService paperService;

    @Override
    public IPage<UserExamRespDTO> paging(PagingReqDTO<UserExamReqDTO> reqDTO) {

        //转换结果
        IPage<UserExamRespDTO> pageData = baseMapper.paging(reqDTO.toPage(), reqDTO.getParams());
        return pageData;
    }

    @Override
    public IPage<UserExamRespDTO> myPaging(PagingReqDTO<UserExamReqDTO> reqDTO) {

        UserExamReqDTO params = reqDTO.getParams();

        if (params == null) {
            params = new UserExamReqDTO();
        }

        params.setUserId(UserUtils.getUserId());


        //转换结果
        IPage<UserExamRespDTO> pageData = baseMapper.paging(reqDTO.toPage(), params);
        return pageData;
    }

    @Override
    public void joinResult(String userId, String examId, Integer score, boolean passed) {

        //查询条件
        QueryWrapper<UserExam> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(UserExam::getUserId, userId)
                .eq(UserExam::getExamId, examId);

        UserExam record = this.getOne(wrapper, false);
        if (record == null) {
            record = new UserExam();
            record.setCreateTime(new Date());
            record.setUpdateTime(new Date());
            record.setUserId(userId);
            record.setExamId(examId);
            record.setMaxScore(score);
            record.setPassed(passed);
            this.save(record);
            return;
        }

        // 修复低分数不加入统计问题
        record.setTryCount(record.getTryCount() + 1);
        record.setUpdateTime(new Date());

        if (record.getMaxScore() < score) {
            record.setMaxScore(score);
            record.setPassed(passed);
        }

        this.updateById(record);

    }

    @Override
    public List<UserExam> listByExamId(String examId) {
        QueryWrapper<UserExam> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(UserExam::getExamId, examId);
        return this.list(wrapper);
    }

    @Override
    public ExamStatisticsRespDTO statisticExamNum(String examId) {
        ExamStatisticsRespDTO respDTO = new ExamStatisticsRespDTO();
        Exam exam = examService.getById(examId);
        if (exam == null){
            throw new ServiceException(-1, "未找到该场考试数据！");
        }
        // 按照考试类型计算考试总人数
        int totalNum = 0;
        if (exam.getOpenType().equals(OpenType.OPEN)) {     //完全公开
            totalNum = userService.calcStudNum();
        }else if (exam.getOpenType().equals(OpenType.DEPT_OPEN)){   //对班级开放
            List<String> deptIds = examDepartService.listByExam(examId);
            for (String deptId : deptIds) {
                totalNum += departService.calcDeptNum(deptId);
            }
        }else if (exam.getOpenType().equals(OpenType.LESSON_OPEN)){
            ExamLesson examLesson = examLessonService.getByExamId(examId);
            totalNum = userLessonService.calcStudNum(examLesson.getLessonId(), exam.getTeacherId());
        }

        // 已考人数：包含所有状态的试卷（考试中，考试结束，待阅卷）
        Integer examNum = paperService.calcPaperNum(examId);

        //待阅卷数量
        Integer noReviewNum = paperService.calcReviewPaperNum(examId);
        Integer reviewNum = paperService.calcNoReviewPaperNum(examId);

        //统计优秀、合格、不及格人数
        int goodNum = 0;
        int passNum = 0;
        int noPassNum = 0;
        List<UserExam> userExamList = this.listByExamId(examId);
        for (UserExam userExam : userExamList) {
            if (userExam.getMaxScore() >= exam.getTotalScore()*0.9){     //大于等于 90%总分算优秀
                goodNum++;
            }else if (userExam.getMaxScore() >= exam.getQualifyScore()){
                passNum++;
            }else {
                noPassNum++;
            }
        }

        respDTO.setTotalNum(totalNum);
        respDTO.setExamNum(examNum);
        respDTO.setNoExamNum(totalNum - examNum);
        respDTO.setNoReviewNum(noReviewNum);
        respDTO.setReviewNum(reviewNum);
        respDTO.setGoodNum(goodNum);
        respDTO.setPassNum(passNum);
        respDTO.setNoPassNum(noPassNum);

        return respDTO;
    }
}
